package com.web_bloks.http.client;

import com.google.gwt.json.client.JSONException;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.Response;
import com.web_bloks.system.client.Logger;

/**
 * JSON Http call
 * - One JSONCallbackListener can be registered
 * - Received JSON data must be an object literal
 * 
 * @author Jean-Lou Dupont
 *
 */
public class JSONCall extends HttpCall {
	
	JSONCallback cb = null;
	
	/*========================================================
	 * ctor
	 ========================================================*/

	public JSONCall() {
		super();
	}
	
	/*========================================================
	 * API 
	 ========================================================*/
	public void setCallback(JSONCallback cb) {
		this.cb = cb;
	}
	
	/*========================================================
	 * REQUESTCALLBACK
	 ========================================================*/
	public void onError(Request request, java.lang.Throwable exception ) {
		Logger.logInfo( this.getClass()+".onError");

		if (cb != null)
			this.cb.onJSONCallError( request, exception );
		
		this.request = null;
	}
	
	public void onResponseReceived(Request request, Response response) {
		int code = response.getStatusCode();
		
		Logger.logInfo( this.getClass()+".onResponseReceived, code=" + code);
		
		if (cb != null) {
			
			if (code == 200)
				this.cb.onJSONCallResponseReceived(code, processResponse(response));
			else
				this.cb.onJSONCallError(request, null);
		}
			
		this.request = null;
	}

	protected JSONValue processResponse(Response response) {
	
		JSONObject data = null;
		JSONValue value = null;
		
		try {
			value = JSONParser.parse( response.getText() );
		} catch(JSONException e) {
			throw new RuntimeException(this.getClass()+".processResponse: can't parse response data to JSON object");
		}
		
		data = value.isObject();
		if (null == data) {
			throw new RuntimeException(this.getClass()+".processResponse: data must be an object");
		}

		return value;
	}
	
}//END